﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;

public partial class employeeSearch : System.Web.UI.Page
{
    //inject EmployeeBLL
    private IEmployeeBLL empBLL = Factory<IEmployeeBLL>.CreateInstance();

    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(employeeSearch).Name);


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Inits();
        }

        //get from viewstate to load data for itemcommand of repeater
        if (ViewState["objEmployee"]!=null)
	    {
            Employee emp = (Employee)ViewState["objEmployee"];
           
           if(!string.IsNullOrEmpty(hdnMenu.Value))
           {
               if (hdnMenu.Value.Equals("SHIFT_GRANT"))
            		 LoadToGrid(emp);
                else
                {
                    if (ViewState["Working"] != null)
                    {
                        Working work = (Working)ViewState["Working"];
                        LoadToGridTimeTracking(emp, work);
                    }
                    
                }
                
	            
           }

            
	    }
    }

    private void Inits()
    {
        //register javascript
        btnSearch.Attributes.Add("onmouseover", "this.src='images/search_hover.gif'");
        btnSearch.Attributes.Add("onmouseout", "this.src='images/search.gif'");
        btnReset.Attributes.Add("onmouseover", "this.src='images/xoa_hover.gif'");
        btnReset.Attributes.Add("onmouseout", "this.src='images/xoa.gif'");

       
        //disable list bar
        //pnlist.Visible = false;
        CodeRadioActive();

        //handle form
        string strMenu = "";
        string fromShiftGrant = "";
        if (Session["Shift"]!=null)
            fromShiftGrant = Session["Shift"].ToString();
        if (this.Context.Items["Menu"] != null || !String.IsNullOrEmpty(fromShiftGrant))
        {
            if (this.Context.Items["Menu"] == null)
                strMenu = "SHIFT_GRANT";
            else
                strMenu = this.Context.Items["Menu"].ToString();
            //save to hidden
            hdnMenu.Value = strMenu;
            //Gan ca
            if (strMenu.Equals("SHIFT_GRANT") || !String.IsNullOrEmpty(fromShiftGrant))
            {
                DateGroup.Visible = false;
                Session.Remove("Shift");
            }//Do bang cham cong
            else
            {
                codeControl.Visible = false;
                SearchRadioActive();
                rdoSearch.Visible = false;
                litFistName.Visible = true;
            }

            //Save menu to hidden
            hdnMenu.Value = strMenu;
        }
        
    }

    private void Reset(bool activeCode)
    {
        if (activeCode)
        {
            CodeRadioActive();
            txtCode.Text = "";
        }
        else
            SearchRadioActive();
        
        txtFirstName.Text = "";
        txtLastName.Text = "";
        foreach (ListItem li in chkGender.Items)
        {
            li.Selected = false;
        }
        cbxPosition.SelectedValue = "";
        msgResult.Visible = false;
        //CodeRadioActive();
    }


    /// <summary>
    /// Search
    /// </summary>
    private void Search(bool Code)
    { 
        //init BO and set control values
        Employee emp = new Employee();

        //use for time Tracking page
        Working work = new Working();

        //search basic
        if (Code)
        {
            emp.Code = txtCode.Text;
        }
        else {
            emp.FirstName = txtFirstName.Text;
            emp.LastName = txtLastName.Text;

            string strTemp = "";
            foreach (ListItem li in chkGender.Items)
            {
                if (li.Selected)
                {
                    strTemp += chkGender.SelectedValue;
                }
            } 
            if (!String.IsNullOrEmpty(strTemp))
                emp.SearchGender = strTemp;
            emp.Position = cbxPosition.SelectedValue;

            //timeTracking time
            if(!string.IsNullOrEmpty(txtFrom.Text.Trim()))
                work.LoginTime = DateTime.ParseExact(txtFrom.Text.Trim(), Constants.DATE_PATTERN, null);
            if(!string.IsNullOrEmpty(txtTo.Text.Trim()))
                work.LogoutTime = DateTime.ParseExact(txtTo.Text.Trim(), Constants.DATE_PATTERN, null);
                

        }
        //save employee to view state
        ViewState["objEmployee"] = emp;
        //save Working to view state
        ViewState["Working"] = work;
        
        
        if (!string.IsNullOrEmpty(hdnMenu.Value))
        {
            //ShiftGrant page
            if (hdnMenu.Value.Equals("SHIFT_GRANT"))
                LoadToGrid(emp);
                //timeTracking page
            else
                LoadToGridTimeTracking(emp,work);
        }

        
    }

    private void CodeRadioActive()
    {
        txtFirstName.ReadOnly = true;
        txtFirstName.CssClass = "disable width_80";
        txtLastName.ReadOnly = true;
        txtLastName.CssClass = "disable width_59";
        chkGender.Enabled = false;
        chkGender.CssClass = "disable";

        cbxPosition.Enabled = false;
        cbxPosition.CssClass = "disable width_150";

        txtCode.ReadOnly = false;
        txtCode.CssClass = "width_80";
        btnSearch.Enabled = false;
        btnSearch.ImageUrl = "images/search_hover.gif";

        rdoCode.Checked = true;
        rdoSearch.Checked = false;
        
    }

    private void SearchRadioActive()
    {
        txtCode.ReadOnly = true;
        txtCode.CssClass = "disable width_80";

        txtFirstName.ReadOnly = false;
        txtFirstName.CssClass = "width_80";
        txtLastName.ReadOnly = false;
        txtLastName.CssClass = "width_80";
        chkGender.Enabled = true;
        chkGender.CssClass = "";
        cbxPosition.Enabled = true;
        cbxPosition.CssClass = "width_150";

        btnSearch.Enabled = true;
        btnSearch.ImageUrl = "images/search.gif";

    }

    /// <summary>
    /// Use for search employee to see timeTracking
    /// </summary>
    /// <param name="emp"></param>
    /// <param name="fromDate"></param>
    /// <param name="toDate"></param>
    private void LoadToGridTimeTracking(Employee emp, Working work)
    {
        try
        {
            List<Employee> list = empBLL.SearchEmplyeeAndTimeTracking(emp,work);
            if (list.Count>0)
            {
                rptEmployee.DataSource = list;
                rptEmployee.DataBind();
                rptEmployee.Visible = true;

                //set msg
                msgResult.Text = "Có " + list.Count + " nhân viên phù hợp đều kiện tìm kiếm.";
            }
            else
            {
                msgResult.Text = "Không có nhân viên nào phù hợp điều kiện tìm kiếm.";
                rptEmployee.Visible = false;

            }

        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    private void LoadToGrid(Employee emp)
    {
    try
        {
            List<Employee> list = empBLL.Search(emp);
            if (list != null)
            {
                rptEmployee.DataSource = list;
                rptEmployee.DataBind();
                rptEmployee.Visible = true;
                
                //set msg
                msgResult.Text = "Có "+list.Count+" nhân viên phù hợp đều kiện tìm kiếm."; 
            }
            else {
                msgResult.Text = "Không có nhân viên nào phù hợp điều kiện tìm kiếm.";
                rptEmployee.Visible = false;
               
            }

        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }      
        }
    }

    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        Search(false);
    }
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        Reset(rdoCode.Checked);
    }
    protected void rdoCode_CheckedChanged(object sender, EventArgs e)
    {
        CodeRadioActive();
    }
    protected void rdoSearch_CheckedChanged(object sender, EventArgs e)
    {
        SearchRadioActive();
    }
    protected void btnSearchCode_Click(object sender, ImageClickEventArgs e)
    {
        Search(true);
    }

    protected void rptEmployee_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        string strMenu = hdnMenu.Value;
        //Content
         if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ImageButton img = (ImageButton)e.Item.FindControl("imgGrant");
            
            if (strMenu.Equals("TIME_TRACKING"))
            {
                img.ImageUrl = "images/view.gif";
                img.ToolTip = "Xem chi tiết bảng chấm công";
               
            }

            //find gender label
            Label lblGender = (Label)e.Item.FindControl("lblGender");
            if (lblGender.Text.Equals("True"))
                lblGender.Text = "Nam";
            else
                lblGender.Text = "Nữ";
        }
             //Header
         else if (e.Item.ItemType == ListItemType.Header)
         {
             if (strMenu.Equals("TIME_TRACKING"))
             {
                 Label lblAction = (Label)e.Item.FindControl("lblAction");
                 lblAction.Text = "Chi tiết chấm công";
             }
         }
    }

    protected void rptEmployee_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        this.Context.Items["employeeID"] = e.CommandArgument;
        string strMenu = hdnMenu.Value;
        //gan ca
        if (strMenu.Equals("SHIFT_GRANT"))
        {
            Server.Transfer(Constants.SHIFT_GRANT);
        }//Do bang cham cong
        else
        {
            //save to context
            Working working = new Working();
            if (!string.IsNullOrEmpty(txtFrom.Text.Trim()))
                working.LoginTime = DateTime.ParseExact(txtFrom.Text.Trim(),Constants.DATE_PATTERN,null);
            if (!string.IsNullOrEmpty(txtTo.Text.Trim()))
                working.LogoutTime = DateTime.ParseExact(txtTo.Text.Trim(), Constants.DATE_PATTERN, null);
            
            this.Context.Items["Working"] = working;
            Server.Transfer(Constants.TIME_TRACKING);
        }

        
        



    }
   
}